#! /usr/bin/env python
# coding=utf-8





import os
import shutil
import threading
import argparse
from argparse import RawTextHelpFormatter
import sys

parser = argparse.ArgumentParser(
    description='''批量运行 NGSpeciesID
    用法: 首先需要 使用conda 进入 NGSpeciesID的环境才行  
    conda activate NGSpeciesID
    run_NGSpeciesID.py -i cutprimer -o ngsp_out -c 6 -t 32 
    由大天才于2021年7月19日创建于浙江农业大学''',formatter_class=RawTextHelpFormatter)



parser.add_argument('-i',
                help='输入的包含很多用于获得一致序列的原始扩增子序列,每个标本放在一个特定的fastq文件中')

parser.add_argument('-o',
                help='输出路径')

parser.add_argument('-t',
                help='并行数 默认为2')

parser.add_argument('-c',
                help='小并行数 默认为2')



args = parser.parse_args()


if not args.i or not args.o:
    parser.print_help()
    sys.exit()



if not args.t:
	thread = 2
else:
	thread = int(args.t)
if not args.c:
	core = 2
else:
	core = int(args.c)



infile = args.i

outfile = args.o



try:
	shutil.rmtree(outfile)
except:
	pass


try:
	os.mkdir(outfile)
except:
	pass



index = 0


thread_pool = []


def run_func(infold,outfold):

	global index
	global core

	index = index + 1

	a = os.system('NGSpeciesID --t %s --isoseq --consensus --medaka --fastq %s --outfolder %s' % (core,infold,outfold))

	if index >= len(thread_pool):
		return None
	else:
		thread_pool[index].start()

	return	None


n = 0

for i in os.listdir(infile):
	seq_id = '.'.join(i.split('.')[:-1])
	fix = i.split('.')[-1]
	if fix in ['fastq','fq']:
		infold = infile+'/'+i
		outfold = outfile+'/'+seq_id
		n += 1
		th = threading.Thread(target=run_func, args=[infold, outfold], name='th_'+str(n))
		thread_pool.append(th)



for i in range(thread):
	if len(thread_pool)>i:
		thread_pool[i].start()
